#include "client.h"

#include <QApplication>
#include <QSettings>
#include <QMessageBox>
#include <QProcess>
#include <QDir>
#include "ipset.h"

#include <QDebug>

void f_Reboot();
int f_ColdBoot(Client *parent, QSettings *config);

int main(int argc, char *argv[])
{ 
    QApplication a(argc, argv);  
    Client w;
    QSettings *config;

    try {
       config = new QSettings("./Config/Config.ini", QSettings::IniFormat);
    } catch (std::bad_alloc) {
        QMessageBox::critical(&w, "错误", "申请内存空间失败!", QMessageBox::Yes);

        delete config;
        return -1;
    }

    if((!config->value("BOOT/COLDBOOT").isValid())
            || (config->value("BOOT/COLDBOOT").toString() == "true"))
    {
        config->setValue("BOOT/COLDBOOT", "true");

        if(f_ColdBoot(&w, config))
        {
            return 0;
        }
        else
        {
            config->setValue("BOOT/COLDBOOT", "false");
        }
    }
    else if(!config->contains("DATA/IP")
            || !config->contains("DATA/PORT")) //配置文件存在但是读不到
        {
            QMessageBox::information(&w, "提示",
                                     "配置项丢失，程序将重启以恢复初始状态!",
                                     QMessageBox::Yes);
            config->clear();
            delete config;

            f_Reboot();

            return 0;
        }
    delete config;

    w.f_UpdateUI();
    w.f_StartTCPConnection();
    w.show();
    return a.exec();
}

void f_Reboot()
{
    QString t_program = QApplication::applicationFilePath();
    QStringList t_arguments = QApplication::arguments();
    QString t_working_directory = QDir::currentPath();
    QProcess::startDetached(t_program, t_arguments, t_working_directory);
    qApp->exit();
}


int f_ColdBoot(Client *parent, QSettings *config)
{
    int ans = QMessageBox::information(parent, "提示",
                             "可能是配置文件不合规范或者首次启动软件\n单击确定进入IP地址配置页面",
                             "确定", "取消");
    if(ans == 1)
    {
        return 1;
    }
    else
    {
        IPSet *widget_IPSet = new IPSet();
        if(!widget_IPSet->exec())
        {
            delete widget_IPSet;
            return 1;
        }
        else
        {
            QString IPAddress = widget_IPSet->f_GetIPAddress();
            QString Port = widget_IPSet->f_GetPort();

            parent->f_SetIPAddress(IPAddress);
            parent->f_SetPort(Port);

            if(config)
            {
                config->setValue("DATA/IP", IPAddress);
                config->setValue("DATA/PORT", Port);
            }

            delete widget_IPSet;
            return 0;
        }
    }
}
